import React, { ReactElement } from "react";
import Layout from "./Layout";
import { Button, Form, Input, message, Result } from "antd";
import { SigninPayload } from "@/models/auth/action";
import { useDispatch, useSelector } from "react-redux";
import { AuthState, AUTH_EFFECT } from "@/models/auth";
import { Redirect, useHistory } from "react-router-dom";
import { RootState } from "@/models";
import { isAuth } from "@/helps/auth";
import { Jwt } from "@/models/auth/dto";
interface Props {}

export default function Signin(props: Props): ReactElement {
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const history = useHistory();
  const auth = useSelector<RootState, AuthState>((state) => state.auth);
  console.log(auth);

  const showError = () => {
    console.log(auth.signin.loaded);
    console.log(!auth.signin.success);
    if (auth.signin.loaded && !auth.signin.success) {
      console.log("...........error");
      return (
        <Result
          status="warning"
          title="登录失败"
          subTitle={auth.signin.message}
        />
      );
    }
  };
  const redirectToDashboard = () => {
    const auth = isAuth();
    if (auth) {
      const {
        user: { role },
      } = auth as Jwt;
      if (role === 0) {
        //注册用户
        return <Redirect to="/user/dashboard" />;
      } else {
        //管理员
        return <Redirect to="/admin/dashboard" />;
      }
    }
  };

  const onFinish = async (value: SigninPayload) => {
    console.log(value);
    const res = (await dispatch({
      type: AUTH_EFFECT.handleSignin,
      payload: value,
    })) as any;
    console.log(res);
    if (res?.status === 200) {
      message.success("登录成功");
      // history.push("/");
    } else {
      message.error(res);
    }
  };
  const signinForm = () => {
    return (
      <Form form={form} onFinish={onFinish}>
        <Form.Item name="email" label="邮箱">
          <Input></Input>
        </Form.Item>
        <Form.Item name="password" label="密码">
          <Input.Password></Input.Password>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    );
  };
  return (
    <Layout title="登录" subTitle="">
      {redirectToDashboard()}
      {showError()}
      {signinForm()}
    </Layout>
  );
}
